# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  
@software: PyCharm 
@file: decorator_class.py 
@time: 2019/2/25 11:09
"""
'''
装饰器定义为类
'''

import types
from functools import wraps

class Profiled:
    def __init__(self, func):
        wraps(func)(self)
        self.ncalls = 0

    def __call__(self, *args, **kwargs):
        self.ncalls += 1
        return self.__wrapped__(*args, **kwargs)

    def __get__(self, instance, owner):
        if instance is None:
            return self
        else:
            return types.MethodType(self, instance)

# 把类做为一个普通的装饰器来使用,放在类里面或外面都可以
@Profiled
def add(x, y):
    return x + y

class Spam:
    @Profiled
    def bar(self, x):
        print(self, x)
if __name__ == '__main__':
    print(add(2, 3))
    print(add(4, 5))
    s = Spam()
    s.bar(1)
    s.bar(2)
    s.bar(3)
    print(Spam.bar.ncalls)